<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-1-8
 * Time: 下午6:00
 * 站点管理
 */
namespace Factory\Controller;
use Mcit\Page;
class SiteController extends BaseController {

    //首页
    public function index(){
        //2---厂商  3---运营商
        if(session('fac_type') == 2){
            if (session('fac_key')){
                $uid = session("fac_key");
                $map[] = array('yy_user_id'=>session('uid'));
            }else{
                $uid = session("fac_login_name");
            }
            $map[] = array('plant_type'=>$uid);
        }elseif(session('fac_type') == 3){
            $map[] = array('plant_attr'=>3);
            if(session('pid') != 0){
                $map[] = array('yy_user_id'=>session('uid'));
            }else{
                $yyuserid = M()->query("select id from ev_fac where id='".session('uid')."' OR pid='".session('uid')."'");
                foreach($yyuserid as $k=>$v){
                    $yyuserids .= $v['id'].",";
                }
                $yyuserids = trim($yyuserids,',');
                $map['yy_user_id'] = array('IN',$yyuserids);
            }
        }

        if(!empty($_GET['plant_attr'])){
            $plant_attr = I("plant_attr");//此字段为区分自营与非自营
            if($plant_attr == 1){//全部
            }elseif($plant_attr == 2){//自营---厂商
                $map['plant_attr'] = array('EQ',2);
            }elseif($plant_attr == 3){//非自营---运营商
                $map['plant_attr'] = array('EQ',1);
            }
        }

        if(!empty($_GET['current_state'])){
            $map['current_state'] = array('like','%'.I('current_state').'%');
        }
        if(!empty($_GET['name'])){
            $map['name'] = array('like','%'.I('name').'%');
        }

        if(!empty($_GET['location_f_1'])){

            if(I('location_s_1') == 110100 || I('location_s_1') == 120100 || I('location_s_1') == 310100 || I('location_s_1') == 500100){
                if(I('location_s_1') == I('location_t_1')-1){
                    $location = I('location_f_1').",".I('location_s_1');
                }else{
                    $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
                }
            }else if(I('location_s_1') == I('location_t_1')-1){
                $location = I('location_f_1').",".I('location_s_1');
            }else{
                $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
            }
            $map['location'] = array('like','%'.$location.'%');
        }
        
        //分页
        $count = M("plant")->where($map)->count();
//        echo M()->getLastSql()."<br />";
        vendor('Mcit.Sys.Page');
        $Page = new Page($count, 20);
        $pageView = $Page->show();
        $this->assign('pageView', $pageView); //发送分页
        $nowPage = isset($_GET['page']) ? $_GET['page'] : 1;
        $plant = M("plant")->where($map)->order("id")->page($nowPage . ',' . $Page->listRows)->select();
//        echo M()->getLastSql();
        //分页结束
        foreach($plant as $k=>$v){
            //将数字的地址转换成文字
            $region = strsToArray($v['location']);
            $regionOne = D("Admin/Region")->where("code='".$region[2]."'")->field("fullname")->find();
            $plant[$k]['location'] = $regionOne['fullname'];
            if(mb_strlen($v['name'],"utf-8") <= 17){
                $plant[$k]['name_text'] = $v['name'];
            }else{
                $plant[$k]['name_text'] = mb_substr($v['name'],0,17,"utf-8")."···";
            }

        }
        //P($plant);
        $this->china = D("Admin/Region")->getChinaArea();
        $this->assign("plant",$plant);
        $this->display();
    }
    //测试方法
    public function test(){
        /*P($_FILES);
        dump($_POST);*/
            //上传
    }
    //添加站点页面
    public function add(){
//        P($_SESSION);
        if(IS_POST){
//            P($_POST);die;
            $data = $_POST;
                //上传
                $config = array(
                    'maxSize'       =>  3145728, //上传的文件大小限制 (0-不做限制)
                    'exts'          =>  array('jpg', 'gif', 'png', 'jpeg'), //允许上传的文件后缀
                    'autoSub'       =>  true, //自动子目录保存文件
                    'subName'       =>  array('date', 'Y-m-d'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                    'rootPath'      =>     './Public/', //保存根路径
                    'savePath'      =>  './data/upload/', //保存路径
                    'saveName'      =>  array('uniqid', ''), //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
                );
                $upload = new \Think\Upload($config); // 实例化上传类
                $info = $upload->upload();
                if (!$info) { // 上传错误提示错误信息
                    //$this->error($upload->getError());
                } else { // 上传成功 获取上传文件信息
                    $photo = $info[photo][savepath].$info[photo][savename];
                }
            $data['photo'] = $photo;
            $data['location'] = $_POST['location_f_1'].",".$_POST['location_s_1'].",".$_POST['location_t_1'];
            //区号start
            if(I('location_f_1') == 110000){
                $data['area_code'] = '010';
            }elseif(I('location_f_1') == 120000){
                $data['area_code'] = '022';
            }elseif(I('location_f_1') == 310000){
                $data['area_code'] = '021';
            }elseif(I('location_f_1') == 500000){
                $data['area_code'] = '023';
            }else{
                $re = M("region")->where("code='".I("location_s_1")."'")->getField("name");
                if(mb_strlen($re,"utf-8") == 3){
                    $re   = mb_substr($re,0,2,"UTF-8");
                }else if(mb_strlen($re,"utf-8") == 4){
                    $re   = mb_substr($re,0,3,"UTF-8");
                }else if(mb_strlen($re,"utf-8") == 5){
                    $re   = mb_substr($re,0,4,"UTF-8");
                }
                $con['city'] = array("like",$re."%");
                $data['area_code']  = M("area_code")->where($con)->getField("area");
            }
            //区号end
            $data['oper_city']  = M("oper_city")->where("oper_id='".$_POST['oper_id']."'")->getField("oper_city");
            $data['province']   = M("region")->where("code='".$_POST['location_f_1']."'")->getField("name");
            $data['city']       = M("region")->where("code='".$_POST['location_s_1']."'")->getField("name");
            //2---厂商  3---运营商
            if(session('fac_type') == 2){
                if (session('fac_key')){
                    $data['plant_type'] = session("fac_key");
                }else{
                    $data['plant_type'] = session("fac_login_name");
                }
                $data['plant_attr'] = 2;
            }elseif(session('fac_type') == 3){
                $data['plant_attr'] = 3;
            }
            $data['yy_user_id'] = session('uid');
            $result = M('plant')->data($data)->add();
            if($result > 0){
                $this->redirect("Site/index");
            }else{
                $this->error("添加失败，请重试！");
            }
        }
        $this->oper  = M("oper")->where(1)->select();
        $this->fac   = M("fac")->where(1)->select();
        $this->china = D("Admin/Region")->getChinaArea();
        $this->display();
    }
    //查看详细页
    public function detail(){
        if(IS_GET){
            $plantOne = M("plant")->where("id='".I('id')."'")->find();
            //将数字的地址转换成文字
            $region = strsToArray($plantOne['location']);
            $regionOne = D("Admin/Region")->where("code='".$region[2]."'")->field("fullname")->find();
            $plantOne['location'] = $regionOne['fullname'];
            $plantOne['oper_city'] = M("oper_city")->where("oper_id='".$plantOne['oper_id']."'")->getField("oper_city");
            $plantOne['oper_id'] = M("oper")->where("id='".$plantOne['oper_id']."'")->getField("oper_name");
            $plantOne['booking'] = $plantOne['booking'] == 1 ? 支持:不支持;
            if($plantOne['evc_type'] == 1){
                $plantOne['evc_type'] = "直流";
            }elseif($plantOne['evc_type'] == 2){
                $plantOne['evc_type'] = "交流";
            }else{
                $plantOne['evc_type'] = "混合";
            }
            $plantOne['wifi'] = $plantOne['wifi'] == 1 ? 支持:不支持;
            if($plantOne['floor'] == 1){
                $plantOne['floor'] = "停车楼";
            }elseif($plantOne['floor'] == 2){
                $plantOne['floor'] = "室外";
            }else{
                $plantOne['floor'] = "地下室";
            }
            if($plantOne['charge_port_type'] == 1){
                $plantOne['charge_port_type'] = "国标";
            }elseif($plantOne['charge_port_type'] == 2){
                $plantOne['charge_port_type'] = "特斯拉";
            }elseif($plantOne['charge_port_type'] == 3){
                $plantOne['charge_port_type'] = "ABB";
            }else{
                $plantOne['charge_port_type'] = "其他";
            }
            $this->assign("plant",$plantOne);
        }
        $this->display();
    }
    //修改详细信息
    public function update(){
        
        $plant= M("plant")->where("id='".I('id')."'")->find();
        //将数字的地址转换成文字
        $region = strsToArray($plant['location']);
        $region = D("Admin/Region")->where("code='".$region[2]."'")->field("fullname")->find();
        $plant['location_text'] = $region['fullname'];
        $plant['oper_name'] = M("oper")->where("id='".$plant['oper_id']."'")->getField("oper_name");
        $this->assign("plant",$plant);
        $this->assign("region",$region);
        $this->oper = M("oper")->where(1)->select();//运营服务商
        $this->fac   = M("fac")->where(1)->select();//厂商
        $this->china = D("Admin/Region")->getChinaArea();
        if(IS_POST){
            $data = $_POST;
            if($data['location_f'] != 0 && $data['location_s'] != 0 && $data['location_t'] != 0){
                    $data['location'] = $data['location_f'].",".$data['location_s'].",".$data['location_t'];
            }
            if($_FILES['photo']['name'] != ''){
                //上传
                $config = array(
                    'maxSize'       =>  3145728, //上传的文件大小限制 (0-不做限制)
                    'exts'          =>  array('jpg', 'gif', 'png', 'jpeg'), //允许上传的文件后缀
                    'autoSub'       =>  true, //自动子目录保存文件
                    'subName'       =>  array('date', 'Y-m-d'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                    'rootPath'      =>     './Public/', //保存根路径
                    'savePath'      =>  './data/upload/', //保存路径
                    'saveName'      =>  array('uniqid', ''), //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
                );
                $upload = new \Think\Upload($config); // 实例化上传类
                $info = $upload->upload();
                if (!$info) { // 上传错误提示错误信息
                    //$this->error($upload->getError());
                } else { // 上传成功 获取上传文件信息
                    $data['photo'] = $info[photo][savepath].$info[photo][savename];
                    if(file_exists($plant['photo'])){
                        unlink($plant['photo']);
                    }
                }
            } 
            $result = M("plant")->where("id='".$_POST['id']."'")->save($data);
            if($result > 0){
                $this->redirect("Site/index");
            }else{
                //echo M("plant")->getLastSql();
                $this->error("添加失败，请重试！");
            }
        }
        $this->display();
    }
    //删除一条数据（同时此站点下的所有电桩信息都将删除）
    public function del(){
        
        if(IS_GET){
          //删除状态记录数据
          $char = M("char")->where("ev_plant_id='".$_GET['id']."'")->select();
          foreach($char as $v){
              D("Admin/State")->where("key_link='".$v['key_link']."'")->delete();
          }
            //删除电桩表数据
          M("char")->where("ev_plant_id='".$_GET['id']."'")->delete();
            //删除站点图片
            $plant_photo = M("plant")->where("id='".$_GET['id']."'")->getField("photo");
            $plant_url = APP_ROOT_PATH.'/Public'.$plant_photo;
            unlink($plant_url);
            //删除站点数据
            $result = M("plant")->where("id='".$_GET['id']."'")->delete();
            if($result){
                echo 1;
            }else{
                echo 0;
            }
        }else{
            $ids = strsToArray($_POST['ids']);
            $map['id'] = array("IN",$ids);
            $plant = M("plant")->where($map)->select();
            foreach($plant as $val){
//                if($val['plant_attr'] == 2){
                    //删除状态记录数据
                    $char = M("char")->where("ev_plant_id='".$val['id']."'")->select();
                    foreach($char as $v){
                        D("Admin/State")->where("key_link='".$v['key_link']."'")->delete();
                    }
                    //删除电桩表数据
                    M("char")->where("ev_plant_id='".$val['id']."'")->delete();
                    //删除站点图片
                    /*$plant_photo = M("plant")->where("id='".$val['id']."'")->getField("photo");
                    $plant_url = APP_ROOT_PATH.'/Public'.$plant_photo;*/
                    $plant_url = APP_ROOT_PATH.'/Public'.$val['photo'];
                    unlink($plant_url);
                    //删除站点数据
                    $result = M("plant")->where("id='".$val['id']."'")->delete();
//                }
            }
            if($result){
                $return['state'] = 100;
                $return['msg']   = '删除成功！';
            }else{
                $return['state'] = 200;
                $return['msg']   = '删除失败！或因非自营则无权此操作！';
            }
            echo json_encode($return);
            exit;
        }
    }
    //站点的建设状态
    public function changehh(){

        $id        = I('id');
        $value     = I('value');
        $map['id'] = $id;
        $data['current_state'] = $value;
        $result    = M('plant')->where($map)->save($data);

        if($result){
            if($value==3){
                $return['html']  = '<a class="btn btn-warning btn-xs changehh" data-id="'.$id.'" data-info="确定将该站点状态修改为“安装中”？" data-value="2">&nbsp;&nbsp;&nbsp;规划中&nbsp;&nbsp;&nbsp;</a>';
                $return['state'] = 300;
                $return['msg']   = '保存成功';
            }elseif($value==2){
                $return['html']  = '<a class="btn btn-warning btn-xs changehh" data-id="'.$id.'" data-info="确定将该站点状态修改为“运营中”？" data-value="1">&nbsp;&nbsp;&nbsp;安装中&nbsp;&nbsp;&nbsp;</a>';
                $return['state'] = 200;
                $return['msg']   = '保存成功';
            }else{
                $return['html']  = '<a class="btn btn-success btn-xs " data-id="'.$id.'" data-info="确定将该站点状态修改为“规划中”？" data-value="3">&nbsp;&nbsp;&nbsp;运营中&nbsp;&nbsp;&nbsp;</a>';
                $return['state'] = 100;
                $return['msg']   = '保存成功';
            }
        }else{
            $return['state'] = 404;
            $return['msg']   = '保存失败';
        }
        echo json_encode($return);

        exit;
    }
    //站点是否支持实时
    public function changeA(){
        $id        = I('aid');
        $value     = I('avalue');
        $map['id'] = $id;
        $data['is_active'] = $value;
        $results    = M("plant")->where($map)->save($data);
        //echo json_encode(M("plant")->getLastSql());
        if($results){
            if($value==1){
                $return['html'] = '<a class="btn  btn-xs changeA" data-value="0"  data-id="'.$id.'" data-info="确定修改为“不支持实时”？"><img src="'.__ROOT__.'/Public/img/gou.png" alt="是"/></a>';
            }else{
                $return['html'] = '<a class="btn  btn-xs changeA" data-value="1"  data-id="'.$id.'" data-info="确定修改为“支持实时”？"><img src="'.__ROOT__.'/Public/img/cha.png" alt="否"/></a>';
            }
            $return['state'] = 100;
            $return['msg']   = '保存成功';
        }else{
            $return['state'] = 200;
            $return['msg']   = '保存失败';
        }
        echo json_encode($return);
        exit;
    }

    //站点数据导出
    public function export(){
//        echo(1323);die;
        $xlsCell  = array(
            array('id','ID'),
            array('name','站点名称'),
            array('location','所在区域'),
            array('circle','商圈/楼盘'),
            array('coordinate','高德坐标'),
            array('floor','停车处：1，停车楼 2，室外 3，地下室'),
            array('total_ev','总电桩数'),
            array('total_par','总车位数'),
            array('wifi','是否支持WIFI：0，否 1，是'),
            array('establish_time','建立时间'),//10
            array('evc_type','电流类型:1，直流；2，交流；3，混合'),
            array('booking','支持预约：1，可预约；0，否'),
            array('parking','停车处大体位置'),
            array('nature','经营性质 1:私人、2:第三方、3:自营、4;未定'),
            array('regulated','监管方'),
            array('regulated_phone','监管方电话'),
            array('company','建立公司'),
            array('company_phone','建立公司电话'),
            array('private_account','分享用户账号'),
            array('private_name','分享用户名称'),//20
            array('private_phone','分享用户电话'),
            array('state_IP','状态IP'),
            array('address','详细地址'),
            array('current_state','运营状态：1，运营中；2，安装中；3，规划中'),
            array('baiducoordinate','百度坐标'),
            array('chexing','车型'),
            array('area_code','区号'),
//            array('province','所在省'),
//            array('city','所在市'),
            array('coordtype','地图类型：1，高德；2，百度'),//30
            array('is_active','实时：1，是；0，否'),
            array('type','场地性质:1，充电点；2，家庭；3，充电站'),
            array('oper_id','运营服务商'),
            array('charge_port_type','充电接口类型:1，国标；2，特斯拉；3，ABB；4，其他'),
            array('charge_fast_num','快充数量'),
            array('charge_slow_num','慢充数量'),
            array('tel','自营电话'),
            array('plant_type','厂商编号'),
            array('park_fee','停车费参考价'),
            array('charger_fee','充电费参考价'),//40
            array('pay_manner','充电支付方式'),
            array('describes','站点描述')
        );
        //2---厂商  3---运营商
        if(session('fac_type') == 2){
            if (session('fac_key')){
                $uid = session("fac_key");
                $map[] = array('yy_user_id'=>session('uid'));
            }else{
                $uid = session("fac_login_name");
            }
            $map[] = array('plant_type'=>$uid);
        }elseif(session('fac_type') == 3){
            $map[] = array('plant_attr'=>3);
            if(session('pid') != 0){
                $map[] = array('yy_user_id'=>session('uid'));
            }else{
                $yyuserid = M()->query("select id from ev_fac where id='".session('uid')."' OR pid='".session('uid')."'");
                foreach($yyuserid as $k=>$v){
                    $yyuserids .= $v['id'].",";
                }
                $yyuserids = trim($yyuserids,',');
                $map['yy_user_id'] = array('IN',$yyuserids);
            }
        }
        $xlsModel = M('plant');
        $xlsData  = $xlsModel->where($map)->select();
        foreach($xlsData as $k => $v){
            //将数字的地址转换成文字
            $region = strsToArray($v['location']);
            $region = M("region")->where("code='".$region[2]."'")->getField("fullname");
            $xlsData[$k]['location'] = $region;
            $xlsData[$k]['oper_id']  = M("oper")->where("id='".$v['oper_id']."'")->getField("oper_name");

        }
        $this->exportExcel($xlsCell,$xlsData);
    }

    //PHPExcel导出方法
   private  function exportExcel($expCellName,$expTableData){
        $fileName = "Site".date('_YmdHis',time());
        $cellNum  = count($expCellName);
        $dataNum  = count($expTableData);
        Vendor('PHPExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel ();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
            'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

        //填入主标题
        $objPHPExcel->getActiveSheet()->setCellValue('A1', C('COMPANY'));
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('黑体');
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('A3:A3')->getFont()->setBold(true);

        //填入副标题
        $objPHPExcel->getActiveSheet()->setCellValue('A2', '站点列表(导出日期：'.date('Y-m-d',time()).')');
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setName('宋体');
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(16);

        //设置表头行高
        $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(35);
        $objPHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(22);
        $objPHPExcel->getActiveSheet()->getRowDimension(3)->setRowHeight(25);

        //设置居中
        $objPHPExcel->getActiveSheet()->getStyle('A1:AN1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A2:AN2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        //合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A1:AN1');
        $objPHPExcel->getActiveSheet()->mergeCells('A2:AN2');

        //设置自动换行
//        $objPHPExcel->getActiveSheet()->getStyle('A3:AK3')->getAlignment()->setWrapText(true);

        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'3', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+4), $expTableData[$i][$expCellName[$j][0]]);
                $objPHPExcel->getActiveSheet(0)->setCellValueExplicit($cellName[$j].($i+4),$expTableData[$i][$expCellName[$j][0]],\PHPExcel_Cell_DataType::TYPE_STRING);
                //$objPHPExcel->getActiveSheet(0)->getStyle($cellName[$j].($i+4))->getNumberFormat()->setFormatCode("@");
            }
        }

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$fileName.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

}
